<template>
  <view class="user-info-container">
    <!-- 状态栏 -->
    <view class="status-bar">
     
    </view>
    
    <!-- 标题栏 -->
    <view class="header">
      <view class="back-button" @click="goBack">
        <image src="/static/arrow-left.png" mode="aspectFit" class="back-icon"></image>
      </view>
      <text class="title">个人信息</text>
      <view class="placeholder"></view>
    </view>
    
    <!-- 个人信息表单 -->
    <view class="user-info-form">
      <!-- 头像 -->
      <view class="form-item" @click="chooseAvatar">
        <text class="label">我的头像</text>
        <view class="value-container">
          <image class="avatar" :src="userInfo.avatar || '/static/default-avatar.png'" mode="aspectFill"></image>
          <image src="/static/right.png" mode="aspectFit" style="width: 32rpx; height: 32rpx;"></image>
        </view>
      </view>
      
      <!-- 昵称 -->
      <view class="form-item" @click="editNickname">
        <text class="label">我的昵称</text>
        <view class="value-container">
          <text class="value">{{ userInfo.nickname || '未设置' }}</text>
          <image src="/static/right.png" mode="aspectFit" style="width: 32rpx; height: 32rpx;"></image>
        </view>
      </view>
      
      <!-- 性别 -->
      <view class="form-item" @click="chooseSex">
        <text class="label">性别</text>
        <view class="value-container">
          <view class="gender-value">
            <text class="gender-icon" v-if="userInfo.gender === 0">♂</text>
            <text class="gender-icon" style="color: cornflowerblue;" v-else-if="userInfo.gender === 1">♀</text>
            <text class="value">{{ userInfo.gender === 0 ? '女' : userInfo.gender === 1 ? '男' : '未设置' }}</text>
          </view>
          <image src="/static/right.png" mode="aspectFit" style="width: 32rpx; height: 32rpx;"></image>
        </view>
      </view>
      
      <!-- 出生年月 -->
      <view class="form-item" @click="chooseBirthday">
        <text class="label">出生年月</text>
        <view class="value-container">
          <text class="value">{{ userInfo.birthday || '未设置' }}</text>
          <image src="/static/right.png" mode="aspectFit" style="width: 32rpx; height: 32rpx;"></image>
        </view>
      </view>
      
      <!-- 位置 -->
      <view class="form-item" @click="chooseLocation">
        <text class="label">位置</text>
        <view class="value-container">
          <text class="value">{{ userInfo.location || '未设置' }}</text>
          <image src="/static/right.png" mode="aspectFit" style="width: 32rpx; height: 32rpx;"></image>
        </view>
      </view>
    </view>
    
    <!-- 保存按钮 -->
    <view class="save-button-container">
      <button class="save-button" @click="saveUserInfo">保存</button>
    </view>
    
    <!-- 底部安全区 -->
    <view class="bottom-safe-area"></view>
  </view>
</template>

<script>
import { getCurrentUserInfo, updateUserInfoV2 } from '@/api/user.js';

export default {
  data() {
    return {
      userInfo: {
        avatar: '/static/default-avatar.png',
        nickname: '',
        gender: '',
        birthday: '',
        location: ''
      },
      originalUserInfo: null, // 保存原始用户信息，用于比较是否有修改
      isLoading: false
    }
  },
  onLoad() {
    this.fetchUserInfo();
  },
  methods: {
    // 获取用户信息
    fetchUserInfo() {
      uni.showLoading({
        title: '加载中...'
      });
      
      // 从服务器获取最新用户信息
      getCurrentUserInfo().then(res => {
        uni.hideLoading();
        if (res.code === '00000' && res.data) {
          // 设置用户信息
          this.userInfo = {
            userId: res.data.userId,
            avatar: res.data.avatar || '/static/default-avatar.png',
            nickname: res.data.nickname || '',
            gender: res.data.gender === undefined ? '' : Number(res.data.gender),
            birthday: res.data.birthday || '',
            location: res.data.location || '',
            mobile: res.data.mobile || ''
          };
          
          // 保存原始数据，用于比较是否有修改
          this.originalUserInfo = JSON.parse(JSON.stringify(this.userInfo));
        }
      }).catch(err => {
        uni.hideLoading();
        console.error('获取用户信息失败', err);
        uni.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        });
      });
    },
    goBack() {
      uni.navigateBack();
    },
    chooseAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          
          // 显示上传中提示
          uni.showLoading({
            title: '上传中...'
          });
          
          // 上传图片到服务器
          // 注意：这里需要实现图片上传功能，获取到图片URL后再设置到userInfo.avatar
          // 这里简化处理，直接设置本地路径
          this.userInfo.avatar = tempFilePath;
          uni.hideLoading();
          
          // 实际项目中应该上传图片到服务器，获取URL后再设置
          // 示例代码:
          /*
          uni.uploadFile({
            url: 'your-upload-api-url',
            filePath: tempFilePath,
            name: 'file',
            success: (uploadRes) => {
              const data = JSON.parse(uploadRes.data);
              if (data.code === '00000') {
                this.userInfo.avatar = data.data.url;
              }
              uni.hideLoading();
            },
            fail: () => {
              uni.hideLoading();
              uni.showToast({
                title: '上传失败',
                icon: 'none'
              });
            }
          });
          */
        }
      });
    },
    editNickname() {
      uni.showModal({
        title: '修改昵称',
        editable: true,
        placeholderText: '请输入昵称',
        content: this.userInfo.nickname,
        success: (res) => {
          if (res.confirm && res.content) {
            this.userInfo.nickname = res.content;
          }
        }
      });
    },
    chooseSex() {
      uni.showActionSheet({
        itemList: ['男', '女'],
        success: (res) => {
          this.userInfo.gender = res.tapIndex === 0 ? 1 : 0;
        }
      });
    },
    chooseBirthday() {
      const date = new Date();
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      
      const currentDate = `${year}-${month}-${day}`;
      
      uni.navigateTo({
        url: `/pages/date-picker/date-picker?date=${this.userInfo.birthday || currentDate}&start=1900-01-01&end=${currentDate}`,
        events: {
          onDateSelected: (date) => {
            this.userInfo.birthday = date;
          }
        }
      });
    },
    chooseLocation() {
      // 这里可以调用地图选择API
      uni.showModal({
        title: '修改位置',
        editable: true,
        placeholderText: '请输入位置',
        content: this.userInfo.location,
        success: (res) => {
          if (res.confirm && res.content) {
            this.userInfo.location = res.content;
          }
        }
      });
    },
    saveUserInfo() {
      // 检查是否有修改
      if (this.originalUserInfo && JSON.stringify(this.userInfo) === JSON.stringify(this.originalUserInfo)) {
        uni.showToast({
          title: '未做任何修改',
          icon: 'none'
        });
        return;
      }
      
      // 防止重复提交
      if (this.isLoading) return;
      this.isLoading = true;
      
      // 显示加载提示
      uni.showLoading({
        title: '保存中...'
      });
      
      // 调用API保存用户信息
      updateUserInfoV2(this.userInfo).then(res => {
        this.isLoading = false;
        uni.hideLoading();
        
        if (res.code === '00000') {
          // 更新本地缓存
          uni.setStorageSync('user_info', this.userInfo);
          
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          });
          
          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({
            title: res.msg || '保存失败',
            icon: 'none'
          });
        }
      }).catch(err => {
        this.isLoading = false;
        uni.hideLoading();
        
        uni.showToast({
          title: err.msg || '保存失败',
          icon: 'none'
        });
      });
    }
  }
}
</script>

<style lang="scss">
.user-info-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  display: flex;
  flex-direction: column;
}

.status-bar {
  height: 88rpx;
  padding: 0 32rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #ffffff;
  
  .time {
    font-size: 32rpx;
    font-weight: bold;
    color: #000000;
  }
  
  .right-icons {
    display: flex;
    align-items: center;
  }
}

.header {
  height: 88rpx;
  padding: 0 32rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
  
  .back-button {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    
    .back-icon {
      width: 40rpx;
      height: 40rpx;
    }
  }
  
  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333333;
  }
  
  .placeholder {
    width: 60rpx;
  }
}

.user-info-form {
  margin-top: 20rpx;
  background-color: #ffffff;
  
  .form-item {
    padding: 30rpx 32rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:active {
      background-color: #f9f9f9;
    }
    
    .label {
      font-size: 32rpx;
      color: #333333;
    }
    
    .value-container {
      display: flex;
      align-items: center;
      
      .avatar {
        width: 100rpx;
        height: 100rpx;
        border-radius: 50%;
        margin-right: 20rpx;
      }
      
      .value {
        font-size: 32rpx;
        color: #666666;
        margin-right: 20rpx;
      }
      
      .gender-value {
        display: flex;
        align-items: center;
        margin-right: 20rpx;
        
        .gender-icon {
          font-size: 32rpx;
          margin-right: 10rpx;
          
          &:first-child {
            color: #ff6b81;
          }
          
          &:last-child {
            color: #3498db;
          }
        }
      }
    }
  }
}

.save-button-container {
  margin: 60rpx 32rpx;
  
  .save-button {
    height: 88rpx;
    background-color: #8B0000;
    color: #ffffff;
    font-size: 32rpx;
    font-weight: bold;
    border-radius: 44rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    
    &:active {
      opacity: 0.8;
    }
  }
}

.bottom-safe-area {
  height: 68rpx;
}
</style>
